package com.ruoyi.network.websocket;

import java.net.URI;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.network.edge.EdgeNetwork;
import com.ruoyi.network.handler.WebsocketMsgHandler;
import com.ruoyi.network.util.SpringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EdgeWsClient extends WebSocketClient {
	private String name;
	private String ip;
	private String id;

	public EdgeWsClient(URI uri, String id,String name, String ip) {
		super(uri);
		this.id = id;
		this.name = name;
		this.ip = ip;
	}
	public String getId() {
		return id;
	}

	@Override
	public void onOpen(ServerHandshake handshake) {
		log.warn(this.getURI() + " connect success");
	}

	@Override
	public void onMessage(String message) {
		JSONObject msg = JSON.parseObject(message);
		JSONObject param = msg.getJSONObject("param");
		JSONObject command = msg.getJSONObject("command");
		int iCommand = command.getIntValue("iCommand");
		String simpleName = WebsocketMsgHandler.class.getSimpleName();
		String beanKey = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1)  + iCommand;
		if(SpringUtils.applicationContext.containsBean(beanKey)) {
			WebsocketMsgHandler websocketMsgHandler = SpringUtils.applicationContext.getBean(beanKey, WebsocketMsgHandler.class);
			synchronized (beanKey.intern()) {
				websocketMsgHandler.invoke(this,msg);
			}
		}
	}

	@Override
	public void onClose(int code, String text, boolean paramBoolean) {
		log.warn(this.getURI() + " close");

	}

	@Override
	public void onError(Exception e) {

	}

	public static String getRandomNum(int length) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int j = 0; j < length; j++) {
			stringBuilder.append((int) (Math.random() * 9));
		}
		return stringBuilder.toString();
	}

	public void heart() {
		JSONObject message = new JSONObject();
		message.put("command", new JSONObject() {
			{
				put("iProtocol", 10000);
				put("iCommand", 3006);
				put("iAttrVal", 999);
				put("iSeqNum", getRandomNum(9));
				put("szClientId", EdgeWsClient.this.id);
			}
		});
		EdgeNetwork edgeNetwork = SpringUtils.getBean(EdgeNetwork.class);
		message.put("param", new JSONObject() {
			{
				put("terminateId", EdgeWsClient.this.id);
				put("terminateName", EdgeWsClient.this.name);
				put("terminateIp", EdgeWsClient.this.ip);
				put("innerHost", edgeNetwork.getInnerHost());
				put("innerPort", edgeNetwork.getInnerPort());
				
			}
		});
		this.send(message.toJSONString());
	}

}
